import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import { Modal, Row, Col, Form, Card, Input, Select, Icon, Button, message, InputNumber} from "antd";
// import MaintainPerson from '../../Form/MaintainPerson';
import Upload from "../../../components/Upload";
import RegionalSelection from "../../Form/RegionalSelection";
import AssodevChoose from "../../Equipment/Components/AssodevChoose";

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
};

const beforeUpload = file => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJPG) {
    message.error("仅允许上传JPG、PNG文件!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片文件不能大于2MB!");
  }
  return isJPG && isLt2M;
};



@connect(({ repair, global }) => ({
  baseUrl:global.baseUrl,
  loading:repair.loading,
  detaildata:repair.detaildata,
  dictionaries:global.dictionaries,
  selectSource:global.selectSource,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class TaskAdd extends PureComponent {
  constructor(props) {
    super(props);
    this.state={
      fileList: [],
      devChoose:null,
      modalDevChooseVisible: false,
      districtId:0,
      pointId:0,
      maintenanceId:0,
    }
  }

  componentDidMount() {
    const { dispatch, match, location } = this.props;
    const detailId = match.params.id && match.params.id!='detail' ? match.params.id : 0;
    // 维保单位列表
    dispatch({
      type: 'global/fetch_select_maintencompany',
    });
    // // 维修人
    // dispatch({
    //   type: 'global/fetch_select_maintenman',
    // });
    // 区域列表选择
    dispatch({
      type: 'global/fetch_select_district',
    });

    if (detailId==0) {
      const pagesquery = location.query;
      // console.log(pagesquery);
      pagesquery && this.setState({
        devChoose:{
          devId:pagesquery.devId,
          devCode:pagesquery.devCode,
          devName:pagesquery.devName,
        },
        districtId:pagesquery.districtId,
        pointId:pagesquery.pointId,
        maintenanceId:pagesquery.maintenanceId,
      });
      if(pagesquery && pagesquery.districtId & pagesquery.districtId!=0){
        this.props.dispatch({
          type: 'global/fetch_select_point',
          payload: {
            districtId:pagesquery.districtId,
          }
        })
      }
      if(pagesquery && pagesquery.maintenanceId & pagesquery.maintenanceId!=0){
        this.props.dispatch({
          type: 'global/fetch_select_maintenman',
          payload: {
            deptId:pagesquery.maintenanceId,
          }
        })
      }
    }



    if (detailId!==0) {
        // 编辑时 读取详情
        dispatch({
          type: "repair/fetch_repair_info",
          payload: {
            repairId: detailId
          }
        })
        .then(() => {
          //根据区域id，获取点位数据
          const districtId = this.props.detaildata.districtId;
          this.props.dispatch({
            type: 'global/fetch_select_point',
            payload: {
              districtId,
            }
          })
          //根据维保id，获取相关人员
          const deptId = this.props.detaildata.maintenanceId;
          this.props.dispatch({
            type: 'global/fetch_select_maintenman',
            payload: {
              deptId,
            }
          })
        })
        .then(()=>{
          const {baseUrl} = this.props;
          this.setState({
            pointId:this.props.detaildata.pointId,
            districtId:this.props.detaildata.districtId,
            devChoose:{
              devId:this.props.detaildata.devId,
              devCode:this.props.detaildata.devCode,
              devName:this.props.detaildata.devName,
            },
            fileList:this.props.detaildata.repairPhoto && this.props.detaildata.repairPhoto.length>0 ? this.props.detaildata.repairPhoto.map(item=>{
              item.url = baseUrl+item.url;
              return item;
            }) : []
          })
        })
    }
  }


  // 维保单位关联人搜索事件-------------------------------------
  handleSearchMaintain = ( value ) =>{
    const { dispatch } = this.props;
    const maintenanceId=value.maintenanceId;
    const userId=value.userId;
    const loadData=value.loadData;

    this.setState({
      maintenanceId,
    })

    if(userId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_maintenman',
      })
    }

    if(loadData && maintenanceId!==0){
      // userId!=0 && this.handleChageMaintenance(maintenanceId);
      dispatch({
        type: 'global/fetch_select_maintenman',
        payload: {
          deptId:maintenanceId,
        },
      })
    }
  }
  checkMaintain =  (rule, value, callback) => {
    if (value.userId!==0) {
      callback();
      return;
    }
    callback('请选择维保单位及相关人员');
  }





  handleFormSubmit(e)  {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch, match } = this.props;
        const detailId = match.params.id && match.params.id!='detail' ? match.params.id : 0;
        const action = detailId === 0 ? 'add' : 'edit';

        // if(values.taskTime){
        //   values.beginTime = values.taskTime[0].unix() * 1000;
        //   values.endTime = values.taskTime[1].unix() * 1000;
        // }

        if(values.region && values.region.pointId!==0 && values.region.districtId.length>0){
          values.districtId = values.region.districtId[values.region.districtId.length - 1];
          values.pointId = values.region.pointId;
        }


        if(values.maintenanceInfo && values.maintenanceInfo.maintenanceId!==0 && values.maintenanceInfo.userId!=0){
          values.maintenanceId = values.maintenanceInfo.maintenanceId;
          values.repairPerson = values.maintenanceInfo.userId;
        }

        dispatch({
          type: `repair/${action}_repair`,
          payload: {
            ...values,
            region:undefined,
            maintenanceInfo:undefined,
          }
        }).then(() => {
            this.handleReset();
            message.success(detailId === 0 ? "设备已报修" : "维修单已修改成功");
            this.goBack();
        });
      }
    });
  }

  goBack = () => {
    const { dispatch, location, match } = this.props;
    const detailId = match.params.id && match.params.id!='detail' ? match.params.id : 0;
    if(detailId===0){
      router.push({ pathname:`/fault/current/list`});
    }else{
      router.push({ pathname:`/fault/current/list`,  query: { ...location.query} });
    }
  }

  handleReset = () => {
    const { match } = this.props;
    const detailId = match.params.id && match.params.id!='detail' ? match.params.id : 0;
    this.setState({
      fileList: detailId === 0 ? [] : this.props.detaildata.repairPhoto ,
      devChoose:detailId === 0 ? null : {
        devId:this.props.detaildata.devId,
        devCode:this.props.detaildata.devCode,
        devName:this.props.detaildata.devCode,
      },
      modalDevChooseVisible: false,
    })
    this.props.form.resetFields();
  };


  // 显示选择设备弹窗
  handleDevChooseModalVisible= flag => {
    this.setState({
      modalDevChooseVisible: !!flag,
    });
  };

  // 显示选择设备弹窗回调
  handleDevChoose = (value) =>{
    const { form: { setFieldsValue }} = this.props;
    this.setState({
      devChoose:{
        devId:value[0].devId,
        devCode:value[0].devCode,
        devName:value[0].devName
      },
    });
    setFieldsValue({ devId: value[0].devId });
    this.handleDevChooseModalVisible(false);

  }


  // 多图上传时间
  handleChangePicUpload = ({ fileList }) => this.setState({ fileList })

  uploadPic = e => {
    if (Array.isArray(e)) {
      return e;
    }
    const filelist =
      e &&
      e.fileList.reduce((arr, current) => {
        if (
          current.response &&
          current.response.data &&
          current.response.data.token
        ) {
          return arr.concat(current.response.data.token);
        } else {
          if (current.status && current.status === "error") {
            return arr.concat([]);
          } else {
            return arr.concat(current.uid);
          }
        }
      }, []);
    return filelist;
  };


  // 安装点位事件-------------------------------------
  handleSearchDistrict = ( value ) =>{
    const { dispatch } = this.props;
    const districtId=value.districtId[value.districtId.length-1];
    const pointId=value.pointId;
    const loadPoint=value.loadPoint;

    this.setState({
      districtId,
      pointId,
      devChoose:null,
    })

    if(pointId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_point',
      })
    }

    if(loadPoint && districtId!=0){
      dispatch({
        type: 'global/fetch_select_point',
        payload: {
          districtId,
        },
      })
    }




  }
  // 用最后个点位检索成数组
  formatDistrictData = (lastid) =>{
    const district=[];
    if(lastid){
      district.unshift(lastid);
      const {selectSource: {districtData} } = this.props;
      const now = districtData.find(item=>item.districtId===lastid);
      if(now && now.parentId!="0"){
        district.unshift(now.parentId);
        this.formatDistrictDataSec(district,now.parentId);
      }
    }
    return district;
  }
  formatDistrictDataSec = (arr,id) =>{
    const {selectSource: {districtData} } = this.props;
    const now = districtData.find(item=>item.districtId===id);
    if(now && now.parentId!="0"){
      arr.unshift(now.parentId);
      this.formatDistrictDataSec(arr,now.parentId);
    }
    return arr;
  }
  checkDistrict =  (rule, value, callback) => {
    if (value.pointId!==0) {
      callback();
      return;
    }
    callback('请选择区域点位!');
  }



  render() {
    const { match, detaildata, dictionaries, selectSource, loading, baseUrl } = this.props;
    const { modalDevChooseVisible, devChoose, fileList, districtId, pointId, maintenanceId } = this.state;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 }
    };

    const detailId = match.params.id && match.params.id!='detail' ? match.params.id : 0;


    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    return (
       <Card
             // title={ detailId === 0 ? null : `维修单号:${detaildata.repairNum}`}
             bodyStyle={{padding:20}}
       >
            <Form layout="horizontal">
              <Row gutter={24}>
                <Col span={12}>
                  <FormItem {...formItemLayout} label="区域点位" colon={false} >
                    {getFieldDecorator('region',{
                      initialValue: detailId === 0 ? (districtId!=0 && pointId!=0 ? {districtId:this.formatDistrictData(districtId),pointId:pointId} : {districtId:[],pointId:0}) : {districtId:this.formatDistrictData(detaildata.districtId),pointId:detaildata.pointId},
                      rules: [{required: true, message: "请选择区域点位"},{validator: this.checkDistrict}],
                    })(
                      <RegionalSelection
                        districtData={selectSource.districtData}
                        pointData={selectSource.pointData}
                        onChange={this.handleSearchDistrict}
                      />
                    )}
                  </FormItem>

                  <FormItem {...formItemLayout} label="故障现象" colon={false}>
                    {getFieldDecorator("repairPresent", {
                      initialValue: detailId === 0 ? undefined : detaildata.repairPresent,
                      rules: [
                        { required: true, message: "请选择故障现象" },
                      ]
                    })(
                      <Select placeholder="请选择故障现象"   style={{ width: '100%' }}>
                        {dictionaries.repairPresent && dictionaries.repairPresent.map(item => (
                          <Option key={item.value} value={item.value}>{item.label}</Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>

                  <FormItem {...formItemLayout} label="故障描述" colon={false}>
                    {getFieldDecorator("faultDesc", {
                      initialValue: detailId === 0 ? undefined : detaildata.faultDesc,
                      rules: [{ max: 200, message: "不超过200个字" }]
                    })(
                      <TextArea
                        placeholder="请输入故障描述"
                        autosize={{ minRows: 3, maxRows: 6 }}
                      />
                    )}
                  </FormItem>

                  <FormItem {...formItemLayout} label="信息来源" colon={false}>
                    {getFieldDecorator("infoSource", {
                      initialValue: detailId === 0 ? undefined : detaildata.infoSource,
                      rules: [
                        // { required: true, message: "请输入设备名称" },
                      ]
                    })(
                      <Select placeholder="请选择信息来源"   style={{ width: '100%' }}>
                        {dictionaries.infoSource && dictionaries.infoSource.map(item => (
                          <Option key={item.value} value={item.value}>
                            {item.label==="稽查督导" ? <span style={{color:'red'}}>{item.label}</span> : item.label}
                          </Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>

                  {/*
                  <FormItem {...formItemLayout} label="维保单位" colon={false}>
                    {getFieldDecorator("maintenanceInfo", {
                      initialValue: detailId === 0 ? (maintenanceId && maintenanceId!=0 ? {maintenanceId:maintenanceId,userId:0} : {maintenanceId:0,userId:0}) : {maintenanceId:detaildata.maintenanceId,userId:detaildata.repairPerson},
                      // initialValue: detailId === 0 ? {maintenanceId:0,userId:0} : {maintenanceId:detaildata.maintenanceId,userId:detaildata.maintainManId},
                      rules: [{required: true, message: "请选择维保单位及相关人员"},{validator: this.checkMaintain}],
                    })(
                      <MaintainPerson
                        // span={24}
                        placeholder={"请选择维修人"}
                        maintainData={selectSource.maintenance}
                        personnelData={selectSource.maintenman}
                        onChange={this.handleSearchMaintain}
                      />
                    )}
                  </FormItem>

                  <FormItem {...formItemLayout} label="处理时限" colon={false}>
                    {getFieldDecorator("handleTime", {
                      initialValue: detailId === 0 ? undefined : detaildata.handleTime,
                      rules: [
                        // { required: true, message: "请输入设备名称" },
                      ]
                    })(
                      <InputNumber placeholder="请输入" precision={0}  min={0} style={{width:100,marginRight:15}} />
                    )} 小时
                  </FormItem>

                  */}
                </Col>


                <Col span={12}>


                  <FormItem {...formItemLayout} label="报修设备" colon={false}>
                    {getFieldDecorator("devId", {
                      initialValue: devChoose && devChoose.devId ? devChoose.devId : undefined,
                      rules: [
                        // { required: true, message: "请输入设备名称" },
                      ]
                    })(
                      <Input type="hidden"/>
                    )}
                    <Button
                      onClick={() => this.handleDevChooseModalVisible(true)}
                      type="default"
                      disabled={districtId!=0 && pointId!=0 ? false : true}
                    >
                      {devChoose && devChoose.devId ? `${devChoose.devName} (设备编号：${devChoose.devCode})` : '请选择报修设备'}
                    </Button>
                  </FormItem>

                  <FormItem
                    {...formItemLayout}
                    label="设备图片"
                    extra={<span>支持jpg、png<br/>图片大小不超过2M</span>}
                  >
                    {getFieldDecorator("repairPhotoArray", {
                      valuePropName: "file",
                      getValueFromEvent: this.uploadPic
                    })(
                      <Upload
                        listType="picture-card"
                        fileList={fileList}
                        // onPreview={this.handlePreview}
                        onChange={this.handleChangePicUpload}
                        beforeUpload={beforeUpload}
                      >
                        {fileList.length >= 5 ? null : uploadButton}
                      </Upload>
                    )}
                  </FormItem>
                </Col>

              </Row>
              <Row gutter={24} >
                <Col span={24} style={{textAlign:'center',padding:30}}>
                    <Button
                      onClick={this.handleFormSubmit.bind(this)}
                      type="primary"
                      size="large"
                      style={{marginRight:15}}
                      loading={loading.model_submit}
                    >
                      提交
                    </Button>
                    <Button
                      onClick={this.handleReset.bind(this)}
                      type="default"
                      size="large"
                    >
                      重置
                    </Button>
                </Col>
              </Row>
            </Form>

         <Modal
           title={"请选择设备"}
           visible={modalDevChooseVisible}
           onCancel={() => this.handleDevChooseModalVisible(false)}
           width={900}
           destroyOnClose={true}
           footer={null}
           bodyStyle={{padding:0}}
         >
           <AssodevChoose
             dictionaries={dictionaries}
             selectSource={selectSource}
             selectCallBack={this.handleDevChoose}
             assodevChoose={devChoose && [devChoose.devId]}
             districtId={districtId}
             pointId={pointId}
           />
         </Modal>


       </Card>
    );
  }
}
